-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
39 lines (29 loc) · 1001 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected graph
def bfs(self, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=" ")
for neighbor in self.graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
if __name__ == "__main__":
g = Graph()
n = int(input("Enter the number of nodes: "))
edges = int(input("Enter the number of edges: "))
print("Enter the edges (u v):")
for _ in range(edges):
u, v = map(int, input().split())
g.add_edge(u, v)
start = int(input("Enter the starting node: "))
print("BFS Traversal: ", end="")
g.bfs(start)